/**
 * Created by tdzl2003 on 10/16/16.
 */

import {
  Entity,
  RichUtils,
} from 'draft-js';

import {Map} from 'immutable';

export function getCurrentLinkUrl(editorState) {
  var selection = editorState.getSelection();

  return editorState.getCurrentContent()
    .getBlockForKey(selection.getAnchorKey())
    .getCharacterList()
    .slice(selection.getStartOffset(), selection.getEndOffset())
    .map(function (v) {
      const key = v.getEntity();
      const entity = key && Entity.get(key);
      if (entity && entity.getType() === 'LINK') {
        const data = entity.getData();
        return data && data.get('href');
      }
    }).reduce((last, result)=>{
      if (!last || last === result) {
        return last;
      }
      // Not a common url, treat as no url.
      return '';
    });
}

export function setLinkUrl(editorState, href) {
  const entityKey = href ? Entity.create('LINK', 'MUTABLE', Map({href})) : null;
  return RichUtils.toggleLink(editorState, editorState.getSelection(), entityKey);
}
